package blue.web.dao.service;

import blue.commons.enums.*;
import blue.commons.models.KeyValue;
import blue.commons.models.TitleValue;
import blue.dao.base.BaseMapper;
import blue.erp.model.BlueClass;
import blue.erp.model.BlueCourse;
import blue.erp.model.BlueGrade;
import blue.erp.model.SysUser;
import blue.tools.commons.BlueStringUtils;
import blue.web.commons.service.TreeService;
import blue.workevaluate.dao.WorkTaskMapper;
import blue.workevaluate.model.*;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Future;
@Lazy
@Service
public class WorkTaskService extends BaseService {

    @Autowired
    private WorkTaskMapper workTaskMapper;

    @Autowired
    private BlueClassService blueClassService;

    @Autowired
    private BlueCourseService blueCourseService;

    @Autowired
    private TreeService treeService;

    @Autowired
    private SysUserService sysUserService;

    @Lazy
    @Autowired
    private WorkTaskStudentSummerService workTaskStudentSummerService;

    @Autowired
    private BlueGradeService blueGradeService;

    @Autowired
    private WorkSettingService workSettingService;
    @Lazy
    @Autowired
    private WorkStudentQuestionService workStudentQuestionService;

    private final static String cachePrefix_TaskId="WorkTask_TaskId";

    public int deleteBatch(String ids, SysUser sysUser) {
        List<Long> idList= BlueStringUtils.convertString2Num(ids,",");
        WorkTaskExample example=new WorkTaskExample();
        example.createCriteria().andIdIn(idList);
        for(Long taskId:idList){
            clearCache(sysUser.getSchoolid(),taskId);
        }
        return this.getBaseMapper().deleteByExample(example);
    }


    public int save(WorkTask record) {
        if(record==null){
            return 0;
        }

        WorkTaskExample example=new WorkTaskExample();
        WorkTaskExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid());
        clearCache(record.getSchoolid(),record.getId());
        if(record.getId()!=null){
            criteria.andIdEqualTo(record.getId());
        }else {
            criteria.andNameEqualTo(record.getName());
        }

        if(StringUtils.isNotBlank(record.getClassIds())){
            addClassInfo(record);
        }

        return this.baseSave(record,example);
    }


    private void addClassInfo(WorkTask record){
        if(record==null || StringUtils.isBlank(record.getClassIds())){
            return;
        }

        updateStudentCount(record,false);

        //将年级的层次信息持久化到任务中
        BlueClass blueClass=blueClassService.selectByPrimaryKey(BlueStringUtils.convertString2Num(record.getClassIds(),",").get(0),record.getSchoolid(),false);
        if(blueClass!=null){
            BlueGrade blueGrade=blueGradeService.selectByPrimaryKey(blueClass.getGradeid(),record.getSchoolid(),false);
            if(blueGrade!=null){
                record.setGradeLevel(blueGrade.getGradeLevel());
            }
        }
    }

    @Async
    public void updateStudentCount(WorkTask record,boolean isSave){
        if(record.getId()==null || StringUtils.isBlank(record.getClassIds()) || record.getSchoolid()==null){
            return;
        }
        if(StringUtils.isNotBlank(record.getClassIds())){
            List<Long> classIdList=BlueStringUtils.convertString2Num(record.getClassIds(),",");
            Long count=0L;
            for(Long classId:classIdList){
                count+= sysUserService.getStudentCountOfClass(classId,record.getSchoolid(),3);
            }
            record.setStudentcount(count.intValue());
        }
        if(isSave){
            this.save(record);
        }
    }

    public int handleNode(Long taskId,Integer nodeNum,String key,TitleValue newNode,Integer operatorType,Long schoolId){
        if(taskId==null || operatorType==null ||schoolId==null) return 0;
        WorkTask workTask=this.selectById(taskId,schoolId);
        clearCache(schoolId,taskId);
        if(workTask==null) return 0;
        String data=workTask.getData();
        if(OperatorEnum.ADD.getKey()==operatorType){
            for(int i=1;i<=nodeNum;i++){
                data=treeService.getResultTree(key,new TitleValue(String.format("节点%s",i),null,null,null),data,operatorType);
            }
        }else {
            data=treeService.getResultTree(key,newNode,data,operatorType);
        }
        //节点发生了改变，需要重新修正每个问题的数据
        workTask.setStatus((byte) StatusEnum.Normal.getValue());
        workTask.setData(data);
        workTask.setQuestionCount(treeService.getLeafNodes(data).size());
        return this.save(workTask);

    }


    public List<WorkTask> selectByObject(WorkTask record,boolean showName,SysUser sysUser){
        WorkTaskExample example=new WorkTaskExample();
        WorkTaskExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid()).andOperatorEqualTo(sysUser.getId().toString());

        if(record.getId()!=null){
            criteria.andIdEqualTo(record.getId());
        }
        //学生获取本班级的任务
        if(sysUser.getType()!=null && sysUser.getType().intValue()== UserTypeEnum.Student.getKey()){
            List<Long> classIds=new LinkedList();
            if(StringUtils.isNotBlank(sysUser.getClassIds())){
                classIds.addAll(BlueStringUtils.convertString2Num(sysUser.getClassIds(),","));
            }
            classIds.addAll(BlueStringUtils.convertString2Num(sysUser.getGroupIds(),","));

            if(CollectionUtils.isNotEmpty(classIds)){
                for(Long classId:classIds){
                    WorkTaskExample.Criteria criteria1=example.createCriteria().andSchoolidEqualTo(sysUser.getSchoolid()).andClassIdsLike("%"+classId+"%");
                    example.or(criteria1);
                }
            }
        }


        List<WorkTask>  result=this.select(example);
        if(CollectionUtils.isNotEmpty(result)){
            for(WorkTask workTask:result){
                if(showName && StringUtils.isNotBlank(workTask.getClassIds())){
                    List<String> classNameList=new LinkedList();
                    for(Long classId:BlueStringUtils.convertString2Num(workTask.getClassIds(),",")){
                        BlueClass blueClass=blueClassService.selectByPrimaryKey(classId,record.getSchoolid(),false);
                        if(blueClass!=null){
                            classNameList.add(blueClass.getName());
                        }
                    }

                    workTask.setClassNameList(classNameList);
                }

                if(showName && workTask.getCourseid()!=null){
                    BlueCourse blueCourse=blueCourseService.selectByPrimaryKey(workTask.getCourseid(),record.getSchoolid(),false);
                    if(blueCourse!=null){
                        workTask.setCourseName(blueCourse.getName());
                    }
                }

                //增加学生的选课结果
                if(StringUtils.isNotBlank(sysUser.getClassIds()) && sysUser.getType()!=null && sysUser.getType().intValue()== UserTypeEnum.Student.getKey()){
                    WorkTaskStudentSummer workTaskStudentSummer=workTaskStudentSummerService.selectUserTask(workTask.getId(),sysUser.getId(),workTask.getSchoolid());
                    if(workTaskStudentSummer!=null){
                        if(workTaskStudentSummer.getStatus()!=StatusEnum.Complete.getValue()){
                            workTask.setCompletecount(workTaskStudentSummer.getCompleteCount());
                            if(workTask.getCompletecount()!=null && workTask.getQuestionCount()!=null &&
                                    workTask.getCompletecount().intValue()==workTask.getQuestionCount().intValue()){
                                workTaskStudentSummer.setStatus((byte) StatusEnum.Complete.getValue());
                                workTaskStudentSummerService.save(workTaskStudentSummer,true);
                            }
                        }
                        workTask.setStatus(workTaskStudentSummer.getStatus());
                    }else {//如果为空，则说明summer数据还没有创建，需要创建一个
                        workTaskStudentSummer=new WorkTaskStudentSummer();
                        workTaskStudentSummer.setTaskId(workTask.getId());
                        workTaskStudentSummer.setSchoolid(workTask.getSchoolid());
                        workTaskStudentSummer.setUserId(sysUser.getId());
                        workTaskStudentSummerService.save(workTaskStudentSummer,false);
                    }

                    //增加学生的附件信息
                    workTask.setStudentAttachmenturls(workTaskStudentSummer.getAttachmenturls());
                }else {//非学生，也就是老师能看到的数据
                    //已经完成的学生数
                    List completedList=workTaskStudentSummerService.getCompletedList(workTask.getId(),workTask.getSchoolid());
                    if(CollectionUtils.isNotEmpty(completedList)){
                        workTask.setCompletecount(completedList.size());
                    }else {
                        workTask.setCompletecount(0);
                    }

                    if(record.getStudentcount()==null || record.getStudentcount()==0 ||
                            (CollectionUtils.isNotEmpty(completedList) && record.getStudentcount()<completedList.size())){
                        updateStudentCount(workTask,true);
                    }

                }

            }
        }

        return result;
    }


    public WorkTask selectById(Long id,Long schoolId){
        if(id==null || schoolId==null) return null;

        Object cacheObject=redisService.getValue(String.format("%s_%s_%s",cachePrefix_TaskId,schoolId,id));
        if(cacheObject!=null){
            return JSONObject.parseObject(cacheObject.toString(),WorkTask.class);
        }

        Object result=this.selectByPrimaryKey(id,schoolId);
        if(result==null){
            return null;
        }

        if(StringUtils.isNotBlank(((WorkTask) result).getClassIds())){
          List classList=new LinkedList();
          for(Long classId:BlueStringUtils.convertString2Num(((WorkTask) result).getClassIds(),",")){
              BlueClass blueClass=blueClassService.selectByPrimaryKey(classId,schoolId,false);
              if(blueClass!=null){
                  classList.add(new KeyValue(blueClass.getId(),blueClass.getName()));
              }
          }
          ((WorkTask) result).setClasses(classList);
        }

        redisService.setValue(String.format("%s_%s_%s",cachePrefix_TaskId,schoolId,id),JSONObject.toJSONString(result));
        return (WorkTask) result;
    }

    public TitleValue queryNodeByKey(Long taskId,String key,Long schoolId){
        if(taskId==null || schoolId==null) return null;

        WorkTask workTask=selectById(taskId,schoolId);
        if(workTask==null || StringUtils.isBlank(workTask.getData())){
            return null;
        }

        return treeService.getNodeByKey(key,workTask.getData(),true);
    }


    public List<WorkTaskResult> queryStudentResult(Long taskId,Long classid, SysUser sysUser) {

        WorkTask workTask = selectById(taskId, sysUser.getSchoolid());
        if (workTask == null || StringUtils.isBlank(workTask.getData())) {
            return null;
        }

        List<WorkTaskResult> result = new LinkedList<>();

        //获取当前任务对应的setting配置
        HashMap settingMap = workSettingService.selectByTaskId(taskId, sysUser.getSchoolid());
        WorkSetting knowledgeSetting=settingMap.get(SettingTypeEnum.knowledge.getValue())==null?null:JSONObject.parseObject(settingMap.get(SettingTypeEnum.knowledge.getValue()).toString(),WorkSetting.class);
        WorkSetting capabilitySetting=settingMap.get(SettingTypeEnum.capability.getValue())==null?null:JSONObject.parseObject(settingMap.get(SettingTypeEnum.capability.getValue()).toString(),WorkSetting.class);


        List<TitleValue> nodeList = treeService.getLeafNodes(workTask.getData());
        if (CollectionUtils.isNotEmpty(nodeList)) {
            for (TitleValue titleValue : nodeList) {
                if(titleValue==null || StringUtils.isBlank(titleValue.getValue())){
                    continue;
                }
                WorkTaskResult workTaskResult=new WorkTaskResult();
                workTaskResult.setQuestionNumber(titleValue.getIndex());
                workTaskResult.setName(titleValue.getTitle());

                //查询标记结果
                WorkTaskStudentQuestion workTaskStudentQuestion=new WorkTaskStudentQuestion();
                if(classid!=null && classid>0){
                    workTaskStudentQuestion.setClassId(classid);
                }
                workTaskStudentQuestion.setQuestionId(titleValue.getValue());
                workTaskStudentQuestion.setTaskId(workTask.getId());
                workTaskStudentQuestion.setSchoolid(sysUser.getSchoolid());
                List allStudentTags=workStudentQuestionService.selectByObject(workTaskStudentQuestion,false,false);

                //标记个数
                workTaskResult.setAllCount(allStudentTags.size());
                workTaskStudentQuestion.setTagresult(TagEnum.Right.getKey());
                List rightList=new LinkedList();
                if(CollectionUtils.isNotEmpty(allStudentTags)){
                    rightList=workStudentQuestionService.selectByObject(workTaskStudentQuestion,false,false);
                }

                if(CollectionUtils.isNotEmpty(rightList)){
                    workTaskResult.setSuccessCount(rightList.size());
                }else {
                    workTaskResult.setSuccessCount(0);
                }
                workTaskResult.setFailedCount(workTaskResult.getAllCount()-workTaskResult.getSuccessCount());


                if(StringUtils.isNotBlank(titleValue.getExtend())){
                    JSONObject extend=JSONObject.parseObject(titleValue.getExtend());
                    if(StringUtils.isNotBlank(extend.getString("type"))){
                       workTaskResult.setType(extend.getString("type"));
                    }

                    if(StringUtils.isNotBlank(extend.getString("knowledgeIds")) && knowledgeSetting!=null){
                        workTaskResult.setKnowledges(treeService.getNodeListByKeys(extend.getString("knowledgeIds"),knowledgeSetting.getData()));
                    }

                    if(StringUtils.isNotBlank(extend.getString("capabilityIds")) && capabilitySetting!=null){
                        workTaskResult.setCapabilities(treeService.getNodeListByKeys(extend.getString("capabilityIds"),capabilitySetting.getData()));
                    }

                }
               result.add(workTaskResult);

            }
        }

        return result;
    }



    @Async
    public Future<String> dispatchTask(){


        return new AsyncResult<>("任务一完成");
    }


    @Override
    public BaseMapper getBaseMapper() {
        return this.workTaskMapper;
    }

    @Override
    public void clearCache(Long schoolId,Object... extend) {
        if(extend==null || extend.length==0){
            redisService.vagueDelete(String.format("%s_%s",cachePrefix_TaskId,schoolId));
        }else {
            redisService.vagueDelete(String.format("%s_%s_%s",cachePrefix_TaskId,schoolId,extend[0]));
        }
    }

}
